package com.ts.conch.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ts.conch.common.result.CommonResult;
import com.ts.conch.dao.ItsMenuDao;
import com.ts.conch.entity.TsMenu;
import com.ts.conch.service.ItsMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ItsMenuServiceImpl extends ServiceImpl<ItsMenuDao, TsMenu> implements ItsMenuService {
    @Autowired
    private ItsMenuDao menuDao;

    /** 日志打印工具 **/
    private static final Logger logger = LoggerFactory.getLogger(ItsMenuServiceImpl.class);

    @Override
    public CommonResult<?> create(TsMenu menu) {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.create] - 开始运行 - 创建菜单menu:{}", JSON.toJSON(menu));
        CommonResult commonResult = CommonResult.failed("系统异常,新增菜单失败!");
        menu.setCreateTime(new Date());
        updateLevel(menu);
        int result = menuDao.insert(menu);
        if (result == 1) {
            commonResult = CommonResult.success(menu, "新增菜单成功!");
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.create] - 结束运行,返回结果commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> update(TsMenu menu) {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.update] - 开始运行 - 创建菜单menu:{}", JSON.toJSON(menu));
        CommonResult<?> commonResult = CommonResult.failed("系统异常,更新菜单失败!");
        UpdateWrapper<TsMenu> updateWrapper = new UpdateWrapper<TsMenu>();
        updateWrapper.eq("id", menu.getId());
        updateLevel(menu);
        int result = menuDao.update(menu, updateWrapper);
        if (result == 1) {
            commonResult = CommonResult.success(menu, "更新菜单成功!");
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.update] - 结束运行 - 返回结果commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> getItem(String id) {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.getItem] - 开始运行 - 获取菜单详情id:{}", id);
        CommonResult<?> commonResult = CommonResult.failed("系统异常,获取菜单失败!");
        TsMenu menu = menuDao.selectById(id);
        if (menu != null) {
            commonResult = CommonResult.success(menu, "获取菜单成功!");
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.getItem] - 结束运行 - 返回结果commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> delete(String id) {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.delete] - 开始运行 - 删除菜单id:{}", id);
        CommonResult<?> commonResult = CommonResult.failed("系统异常,删除菜单失败!");
        int result = menuDao.deleteById(id);
        if (result != 1) {
            commonResult = CommonResult.success("删除该菜单成功!");
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.delete] - 结束运行 - 返回结果commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> list(Map<String, Object> params) {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.list] - 开始运行 - 分页查询后台菜单params:{}", JSON.toJSON(params));
        CommonResult<?> commonResult = CommonResult.failed("系统异常,查询菜单失败!");
        LambdaQueryWrapper<TsMenu> queryWrapper = new LambdaQueryWrapper<TsMenu>();
        String page = (String) params.get("page");
        String size = (String) params.get("size");
        String parentId = (String) params.get("parentId");
        IPage<TsMenu> pageParams = new Page<TsMenu>();
        pageParams.setCurrent(Long.parseLong(page));
        pageParams.setSize(Long.parseLong(size));
        queryWrapper.eq(TsMenu::getParentId, Long.parseLong(parentId));
        IPage<TsMenu> pageList = menuDao.selectPage(pageParams, queryWrapper);
        if (CollectionUtil.isNotEmpty(pageList.getRecords())) {
            commonResult = CommonResult.success(pageList);
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.list] - 结束运行 - 返回结果commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> treeList() {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.treeList] - 开始运行 - 树形结构返回所有菜单列表，入参:{}", "");
        CommonResult commonResult = CommonResult.failed("系统异常,查询菜单列表出错!");
        LambdaQueryWrapper<TsMenu> queryWrapper = new LambdaQueryWrapper<TsMenu>();
        queryWrapper.eq(TsMenu::getHidden, 0);
        List<TsMenu> menuList = menuDao.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(menuList)) {
            List<TsMenu> resultList = menuList.stream()
                    .filter(menu -> menu.getParentId().equals(0L)).sorted(Comparator.comparing(TsMenu::getSort))
                    .map(menu -> covertMenuNode(menu, menuList)).collect(Collectors.toList());
            commonResult = CommonResult.success(resultList);
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.treeList] - 结束运行 - 返回结果commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> updateHidden(Map<String, Object> params) {
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.updateHidden] - 开始运行 - 修改菜单显示状态params:{}", JSON.toJSON(params));
        CommonResult<?> commonResult = CommonResult.failed("系统异常,更新菜单状态失败!");
        String id = (String) params.get("id");
        String hidden = (String) params.get("hidden");
        TsMenu menu = new TsMenu();
        menu.setId(id);
        menu.setHidden(Integer.parseInt(hidden));
        int result = menuDao.updateById(menu);
        if (result == 1) {
            commonResult = CommonResult.success("", "更新当前菜单状态成功!");
        }
        logger.info("[菜单管理] - 程序[LrMenuServiceImpl.updateHidden] - 开始运行 - 结果返回commonResult:{}", JSON.toJSON(commonResult));
        return commonResult;
    }

    /**
     * 修改菜单层级
     */
    private void updateLevel(TsMenu menu) {
        if (menu.getParentId().equals("0")) {
            //没有父菜单时为一级菜单
            menu.setLevel(0);
        } else {
            //有父菜单时选择根据父菜单level设置
            TsMenu parentMenu = menuDao.selectById(menu.getParentId());
            if (parentMenu != null) {
                menu.setLevel(parentMenu.getLevel() + 1);
            } else {
                menu.setLevel(0);
            }
        }
    }

    /**
     * 将LrMenu设置children属性
     */
    private TsMenu covertMenuNode(TsMenu menu, List<TsMenu> menuList) {
        TsMenu node = new TsMenu();
        BeanUtils.copyProperties(menu, node);
        List<TsMenu> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId())).sorted(Comparator.comparing(TsMenu::getSort))
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
